<template>
  <div class="withdraw-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="header-content">
        <div class="header-left">
          <h2 class="page-title">
            <i class="el-icon-money"></i>
            提现管理
          </h2>
          <p class="page-description">每月15号后可提现上月及以前的收益，通过支付宝转入业务员账户</p>
        </div>
        <div class="header-right">
          <el-button
            icon="el-icon-refresh"
            @click="loadData">
            刷新数据
          </el-button>
        </div>
      </div>
    </div>

    <!-- 收益概览卡片 -->
    <div class="income-overview">
      <el-row :gutter="20">
        <el-col :span="8">
          <div class="overview-card total-income">
            <div class="card-icon">
              <i class="el-icon-coin"></i>
            </div>
            <div class="card-content">
              <div class="card-title">总收益</div>
              <div class="card-value">¥{{ totalIncome.toFixed(2) }}</div>
            </div>
            <div class="income-types">
              <div class="income-type-item adincome-item" @click="goToCommissionDetail(1)">
                <div class="income-type-info">
                  <div class="income-type-title">广告收益</div>
                  <div class="income-type-value">¥{{ adincome.toFixed(2) }}</div>
                </div>
              </div>
              <div class="income-type-item alliance-item" @click="goToCommissionDetail(2)">
                <div class="income-type-info">
                  <div class="income-type-title">异业联盟收益</div>
                  <div class="income-type-value">¥{{ alliancelncome.toFixed(2) }}</div>
                </div>
              </div>
            </div>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="overview-card available-income">
            <div class="card-icon">
              <i class="el-icon-wallet"></i>
            </div>
            <div class="card-content">
              <div class="card-title">可提现金额</div>
              <div class="card-value">¥{{ availableIncome.toFixed(2) }}</div>
            </div>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="overview-card frozen-income">
            <div class="card-icon">
              <i class="el-icon-lock"></i>
            </div>
            <div class="card-content">
              <div class="card-title">冻结金额</div>
              <div class="card-value">¥{{ frozenIncome.toFixed(2) }}</div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 提现时间提示 -->
    <div class="withdraw-time-info">
      <el-alert
        :title="withdrawTimeInfo"
        :type="canWithdraw ? 'success' : 'warning'"
        :closable="false"
        show-icon>
      </el-alert>
    </div>

    <!-- 接口说明提示 -->
    <div class="api-info">
      <el-alert
        title="注意：收益统计功能需要后端提供专门的API接口，目前显示为0。需要以下接口：1. 业务员收益统计接口 2. 业务员收益明细接口"
        type="info"
        :closable="false"
        show-icon>
      </el-alert>
    </div>

    <!-- 操作按钮 -->
    <div class="action-buttons">
      <el-button
        type="primary"
        icon="el-icon-plus"
        :disabled="!canWithdraw || availableIncome <= 0"
        @click="showWithdrawDialog">
        申请提现
      </el-button>
    </div>

    <!-- 收益明细表格 -->
    <div class="income-details">
      <el-card>
        <div slot="header" class="card-header">
          <span>收益明细</span>
          <div class="header-actions">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              @change="handleDateChange">
            </el-date-picker>
            <el-button
              type="primary"
              icon="el-icon-search"
              @click="loadData">
              查询
            </el-button>
          </div>
        </div>

        <configurable-table
          :columns="tableColumns"
          :data="incomeList"
          :loading="loading"
          :show-pagination="true"
          :current-page.sync="pagination.current"
          :page-size.sync="pagination.size"
          :pagination-total="pagination.total"
          @page-change="loadData"
          stripe>
          <!-- 状态列 -->
          <template #status="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </configurable-table>
      </el-card>
    </div>

    <!-- 提现申请对话框 -->
    <el-dialog
      title="申请提现"
      :visible.sync="withdrawDialogVisible"
      width="500px"
      :close-on-click-modal="false">

      <el-form
        :model="withdrawForm"
        :rules="withdrawRules"
        ref="withdrawForm"
        label-width="120px">

        <el-form-item label="可提现金额">
          <span class="available-amount">¥{{ availableIncome.toFixed(2) }}</span>
        </el-form-item>

        <el-form-item label="提现金额" prop="amount">
          <el-input-number
            v-model="withdrawForm.amount"
            :min="0.01"
            :max="availableIncome"
            :precision="2"
            :step="0.01"
            placeholder="请输入提现金额"
            style="width: 100%">
          </el-input-number>
        </el-form-item>

        <el-form-item label="支付宝账号" prop="alipayAccount">
          <el-input
            v-model="withdrawForm.alipayAccount"
            placeholder="请输入支付宝账号"
            maxlength="50">
          </el-input>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="withdrawForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息（可选）"
            maxlength="200">
          </el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="withdrawDialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          :loading="withdrawLoading"
          @click="handleWithdrawSubmit">
          确认提现
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getWithdrawPage, addWithdraw } from '@/api/aggregation'
import { getIncomeStats } from '@/api/salesman/withdraw'

export default {
  name: 'SalesmanWithdraw',
  data() {
    return {
      // 收益数据
      totalIncome: 0,
      availableIncome: 0,
      frozenIncome: 0,
      adincome: 0,        // 广告收益
      alliancelncome: 0,   // 异业联盟收益

      // 表格数据
      incomeList: [],
      loading: false,

      // 表格列配置
      tableColumns: [
        { prop: 'id', label: '记录ID', minWidth: 80 },
        { prop: 'orderNo', label: '订单号', minWidth: 150 },
        { prop: 'merchantName', label: '商家名称', minWidth: 120 },
        {
          prop: 'orderAmount',
          label: '订单金额',
          minWidth: 100,
          align: 'right',
          formatter: (row, column, cellValue) => {
            return `¥${(cellValue || 0).toFixed(2)}`
          }
        },
        {
          prop: 'commissionRate',
          label: '分佣比例',
          minWidth: 100,
          align: 'right',
          formatter: (row, column, cellValue) => {
            return `${((cellValue || 0) * 100).toFixed(1)}%`
          }
        },
        {
          prop: 'commissionAmount',
          label: '分佣金额',
          minWidth: 100,
          align: 'right',
          formatter: (row, column, cellValue) => {
            return `¥${(cellValue || 0).toFixed(2)}`
          }
        },
        {
          prop: 'withdrawableTime',
          label: '可提现时间',
          minWidth: 120,
          formatter: (row, column, cellValue) => {
            return this.formatDate(cellValue)
          }
        },
        {
          prop: 'status',
          label: '状态',
          minWidth: 100,
          slot: 'status'
        },
        {
          prop: 'createTime',
          label: '获得时间',
          minWidth: 150,
          formatter: (row, column, cellValue) => {
            return this.formatDateTime(cellValue)
          }
        }
      ],

      // 分页
      pagination: {
        current: 1,
        size: 10,
        total: 0
      },

      // 日期筛选
      dateRange: [],

      // 提现对话框
      withdrawDialogVisible: false,
      withdrawLoading: false,
      withdrawForm: {
        amount: 0,
        alipayAccount: '',
        remark: ''
      },
      withdrawRules: {
        amount: [
          { required: true, message: '请输入提现金额', trigger: 'blur' },
          { type: 'number', min: 0.01, message: '提现金额必须大于0', trigger: 'blur' }
        ],
        alipayAccount: [
          { required: true, message: '请输入支付宝账号', trigger: 'blur' },
          { min: 5, max: 50, message: '支付宝账号长度在5到50个字符', trigger: 'blur' }
        ]
      }
    }
  },

  computed: {
    // 是否可以提现
    canWithdraw() {
      const now = new Date()
      const currentDay = now.getDate()
      return currentDay >= 15
    },

    // 提现时间信息
    withdrawTimeInfo() {
      if (this.canWithdraw) {
        return '当前可以提现上月及以前的收益'
      } else {
        const now = new Date()
        const nextWithdrawDate = new Date(now.getFullYear(), now.getMonth(), 15)
        return `下次可提现时间：${nextWithdrawDate.toLocaleDateString()}`
      }
    }
  },

  mounted() {
    this.loadData()
  },

  methods: {
    // 加载数据 - 刷新页面所有数据
    async loadData() {
      this.loading = true
      try {
        // 重置分页到第一页
        this.pagination.current = 1
        // 同时加载所有数据，确保数据一致性
        await Promise.all([
          this.loadWithdrawRecords(),
          this.loadIncomeStats()
        ])
        this.$message.success('数据刷新成功')
      } catch (error) {
        Logger.error('加载数据失败:', error)
        this.$message.error('加载数据失败')
      } finally {
        this.loading = false
      }
    },

    // 加载通用收益统计
    async loadIncomeStats() {
      try {
        Logger.log('=== 加载通用收益统计 ===')
        const response = await getIncomeStats()
        Logger.log('通用收益统计响应:', response)

        if (response.code === 0) {
          const data = response.data
          this.adincome = data.adincome || 0
          this.alliancelncome = data.alliancelncome || 0
          this.totalIncome = data.totalIncome || 0
          this.availableIncome = data.availableAmount || 0
          this.frozenIncome = data.pendingAmount || 0
          Logger.log('通用收益统计加载成功:', { adincome: this.adincome, alliancelncome: this.alliancelncome })
        } else {
          Logger.warn('通用收益统计接口返回错误:', response.data)
          this.adincome = 0
          this.alliancelncome = 0
          this.totalIncome = 0
          this.availableIncome = 0
          this.frozenIncome = 0
        }
      } catch (error) {
        Logger.error('加载通用收益统计失败:', error)
        this.adincome = 0
        this.alliancelncome = 0
        this.totalIncome = 0
        this.availableIncome = 0
        this.frozenIncome = 0
      }
    },

    // 加载提现记录
    async loadWithdrawRecords() {
      try {
        const params = {
          pageIndex: this.pagination.current,
          pageSize: this.pagination.size,
          startTime: this.dateRange && this.dateRange[0] ? this.dateRange[0] + ' 00:00:00' : '',
          endTime: this.dateRange && this.dateRange[1] ? this.dateRange[1] + ' 23:59:59' : ''
        }

        const response = await getWithdrawPage(params)
        Logger.log('提现记录响应:', response.data)

        if (response.code === 0 && response.data) {
          // 处理提现记录数据
          this.incomeList = response.data.list || []
          this.pagination.total = response.data.total || 0
        } else {
          this.incomeList = []
          this.pagination.total = 0
        }

      } catch (error) {
        Logger.error('加载提现记录失败:', error)
        this.incomeList = []
        this.pagination.total = 0
        // 不显示错误消息，因为这是后台数据加载
      }
    },

    // 显示提现对话框
    showWithdrawDialog() {
      if (!this.canWithdraw) {
        this.$message.warning('当前时间不可提现，请等待每月15号之后')
        return
      }

      if (this.availableIncome <= 0) {
        this.$message.warning('当前没有可提现的金额')
        return
      }

      this.withdrawDialogVisible = true
      this.resetWithdrawForm()
    },

    // 重置提现表单
    resetWithdrawForm() {
      this.withdrawForm = {
        amount: 0,
        alipayAccount: '',
        remark: ''
      }
      if (this.$refs.withdrawForm) {
        this.$refs.withdrawForm.clearValidate()
      }
    },

    // 处理提现错误提示
    handleWithdrawError(error) {
      // 优先显示 detail 字段的详细信息
      if (error.detail) {
        this.$message.error(error.detail)
        return
      }
      // 其次显示 message 字段
      if (error.message) {
        this.$message.error(error.message)
        return
      }
      // 兼容旧格式的 msg 字段
      if (error.msg) {
        this.$message.error(error.msg)
        return
      }
      // 默认错误提示
      this.$message.error('提现申请失败，请重试')
    },

    // 提交提现申请
    async handleWithdrawSubmit() {
      try {
        await this.$refs.withdrawForm.validate()
        this.withdrawLoading = true

        const params = {
          amount: this.withdrawForm.amount,
          alipayAccount: this.withdrawForm.alipayAccount,
          remark: this.withdrawForm.remark || '',
          userType: 2, // 业务员类型
          userId: this.$store.state.user.id || null // 当前用户ID
        }

        Logger.log('=== 提交业务员提现申请 ===')
        Logger.log('请求参数:', params)

        const response = await addWithdraw(params)
        Logger.log('提现申请响应:', response)

        if (response.data && response.data.code === 0) {
          this.$message.success('提现申请提交成功，请等待审核')
          this.withdrawDialogVisible = false
          this.loadData() // 重新加载数据
        } else {
          // 使用统一的错误处理函数
          const errorData = response.data || response
          this.handleWithdrawError(errorData)
        }

      } catch (error) {
        Logger.error('提现申请失败:', error)
        // 处理异常情况下的错误信息
        if (error.response && error.response.data) {
          this.handleWithdrawError(error.response.data)
        } else if (error.data) {
          this.handleWithdrawError(error.data)
        } else {
          this.$message.error('提现申请失败，请重试')
        }
      } finally {
        this.withdrawLoading = false
      }
    },

    // 日期筛选变化
    handleDateChange() {
      this.pagination.current = 1
      this.loadData()
    },

    // 格式化日期
    formatDate(date) {
      if (!date) return '-'
      return new Date(date).toLocaleDateString()
    },

    // 格式化日期时间
    formatDateTime(dateTime) {
      if (!dateTime) return '-'
      return new Date(dateTime).toLocaleString()
    },

    // 获取状态类型
    getStatusType(status) {
      const statusMap = {
        1: 'success', // 可提现
        2: 'info',    // 已提现
        3: 'warning'  // 冻结
      }
      return statusMap[status] || 'info'
    },

    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        1: '可提现',
        2: '已提现',
        3: '冻结'
      }
      return statusMap[status] || '未知'
    },

    // 跳转到收益详情页
    goToCommissionDetail(platform) {
      // platform: 1=广告收益, 2=异业联盟收益
      this.$router.push({
        name: 'SalesmanIncomeDetail',
        query: { incomeType: platform }
      })
    }
  }
}
</script>

<style scoped>
.withdraw-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 20px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.header-left {
  flex: 1;
}

.header-right {
  display: flex;
  align-items: center;
}

.page-title {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin: 0 0 8px 0;
  display: flex;
  align-items: center;
}

.page-description {
  color: #606266;
  margin: 0;
  font-size: 14px;
}

.income-overview {
  margin-bottom: 20px;
}

.overview-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  padding: 20px;
  color: white;
  display: flex;
  align-items: center;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.overview-card.available-income {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.overview-card.frozen-income {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.overview-card.adincome-card {
  background: linear-gradient(135deg, #409eff 0%, #66b1ff 100%);
}

.overview-card.alliance-card {
  background: linear-gradient(135deg, #9c27b0 0%, #ba68c8 100%);
}

.card-icon {
  font-size: 32px;
  margin-right: 16px;
  opacity: 0.8;
}

.card-content {
  flex: 1;
}

.total-income {
  display: flex;
  align-items: center;
}

.total-income .card-content {
  flex: 1;
}

.income-types {
  display: flex;
  flex-direction: row;
  gap: 24px;
  margin-left: 20px;
  padding-left: 20px;
}

.income-type-item {
  position: relative;
  padding: 4px 15px;
  padding-left: 48px;
  border-radius: 6px;
  background-color: rgba(255, 255, 255, 0.15);
  backdrop-filter: blur(10px);
  transition: all 0.3s;
  cursor: pointer;
}

.income-type-item:hover {
  background-color: rgba(255, 255, 255, 0.25);
  transform: translateY(-1px);
}

.income-type-item::before {
  content: '';
  position: absolute;
  left: 16px;
  top: 50%;
  transform: translateY(-50%);
  width: 4px;
  height: 32px;
  border-radius: 2px;
}

.adincome-item::before {
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.9), rgba(255, 255, 255, 0.7));
}

.alliance-item::before {
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.9), rgba(255, 255, 255, 0.7));
}

.income-type-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.income-type-title {
  font-size: 13px;
  color: rgba(255, 255, 255, 0.9);
  font-weight: 500;
}

.income-type-value {
  font-size: 18px;
  font-weight: 600;
  color: white;
}

.card-title {
  font-size: 14px;
  opacity: 0.9;
  margin-bottom: 4px;
}

.card-value {
  font-size: 24px;
  font-weight: bold;
}

.withdraw-time-info {
  margin-bottom: 20px;
}

.api-info {
  margin-bottom: 20px;
}

.action-buttons {
  margin-bottom: 20px;
}

.action-buttons .el-button {
  margin-right: 10px;
}

.income-details {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}


.available-amount {
  font-size: 16px;
  font-weight: bold;
  color: #67C23A;
}

.dialog-footer {
  text-align: right;
}

.dialog-footer .el-button {
  margin-left: 10px;
}
</style>
